<script setup>
import { computed, ref, reactive, watch } from "vue";
const count = ref(0);
const addCount = () => {
  count.value++;
};
//监听单个值的变化
watch(count, (newValue, oldValue) => {
  console.log("新值:" + newValue + "老值:" + oldValue);
});

//监听多个数据的变化
const age = ref(18);
const name = ref("李四");
const updateAgeAndName = () => {
  age.value++;
  name.value = "王五";
};
watch(
  [age, name], //需要监听的多个数据
  ([newAge, newName], [oldAge, oldName]) => {
    console.log("新值:" + newAge + "老值:" + oldAge);
    console.log("新值:" + newName + "老值:" + oldName);
  }
);
//监听对象的变化
const state = ref({
  age: 0,
  name: "张三",
});
const updateCountAndName = () => {
  state.value.age++;
  state.value.name = "老六";
};
watch(
  //这种方式是直接监听到对象中的属性值，可以被直接监听到，无需开启deep深度监听
  //   [() => state.age, () => state.name],
  //   ([newAge, newName], [oldAge, oldName]) => {
  //     console.log("新值:" + newAge + "老值:" + oldAge);
  //     console.log("新值:" + newName + "老值:" + oldName);
  //   }
  //此种方式，必须开启deep深度监听,但是如果我们的对象是使用reactive()函数声明的，那么也不需要开启deep深度监听
  state,
  () => {
    console.log("对象的值变化了");
  }
  ,
  {
    deep:true
  }
);

//immediate: true 立即执行函数
const totalt = ref(10);
const updateTotal = () => {
  totalt.value++;
};
watch(
  totalt,
  (newValue, oldValue) => {
    console.log("immediate函数已经执行了");
  },
  {
    immediate: true, //一上来就会执行
  }
);
</script>
<template>
  <div>
    <button @click="addCount">{{ count }}</button>
    <p></p>
    <button @click="updateAgeAndName">{{ age }},{{ name }}</button>
    <p></p>
    <button @click="updateCountAndName">
      {{ state.age }},{{ state.name }}
    </button>
    <p></p>
    <button @click="updateTotal">{{ totalt }}</button>
  </div>
</template>

<style scoped>
</style>
